package com.feicheng.common.token;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import com.alibaba.fastjson.JSONObject;
import com.feicheng.common.constant.Constant;
import com.feicheng.common.exception.SystemException;
import com.feicheng.persistence.entity.Client;
import com.feicheng.persistence.entity.Store;
import com.feicheng.persistence.entity.User;

public class TokenBL {
	
	@Lazy
	@Autowired
	protected TokenContainer tokenContainer;
	
	private LocalDateTime ct;
	
	protected Token getCurrentToken() {
		return tokenContainer.getToken(TokenContainer.getCurrentTokenId());
	}
	
	protected Client currentClient() {
		JSONObject currentUserInfo = getCurrentToken().getToken().getJSONObject(Constant.RESULT.CURRENT);
		
		if (null == currentUserInfo) {
			throw new SystemException("取得当前用户失败");
		}
		
        Client client = currentUserInfo.getObject(Constant.ENTITY.CLIENT.TABLE, Client.class);
        return client;
	}
	
	protected User currentUser() {
		JSONObject currentUserInfo = getCurrentToken().getToken().getJSONObject(Constant.RESULT.CURRENT);
		
		if (null == currentUserInfo) {
			throw new SystemException("取得当前用户失败");
		}
		
        User currentUser = currentUserInfo.getObject(Constant.RESULT.USER.USER, User.class);
        return currentUser;
	}
	
	protected Store currentStore() {
		JSONObject currentUserInfo = getCurrentToken().getToken().getJSONObject(Constant.RESULT.CURRENT);
		
		if (null == currentUserInfo) {
			throw new SystemException("取得当前用户失败");
		}
		
        Store store = currentUserInfo.getObject(Constant.RESULT.STORE.STORE, Store.class);
        return store;
	}
	
	protected LocalDateTime ct(Boolean flg) {
		if (flg) {
			ct = LocalDateTime.now();
		}
		return ct;
	}
	
	protected LocalDateTime ct() {
		
		if (null == ct) {
			ct = LocalDateTime.now();
		}
		
		return ct;
	}
	
	protected void setToken(String key, Object value) {
		getCurrentToken().getToken().put(key, value);
	}
	

}
